﻿using System.Configuration;
using System.Net.Mail;
using System.Threading;

namespace Quintsys.Core.Services
{
    public interface IMailService
    {
        /// <summary>
        /// Sends the email.
        /// </summary>
        /// <param name="toEmail">The recipient of this email message.</param>        
        /// <param name="mailMessage">The mail message.</param>
        /// <returns></returns>
        void SendEmail(string toEmail, MailMessage mailMessage);

        /// <summary>
        /// Sends the email.
        /// </summary>
        /// <param name="toEmail">The recipient of this email message.</param>        
        /// <param name="mailMessage">The mail message.</param>
        /// <returns></returns>
        void SendEmail(MailAddress toEmail, MailMessage mailMessage);

        /// <summary>
        /// Sends the email.
        /// </summary>
        /// <param name="mailMessage">The mail message.</param>
        void SendEmail(MailMessage mailMessage);
    }

    public class MailService : IMailService
    {
        /// <summary>
        /// Sends the email.
        /// </summary>
        /// <param name="mailMessage">The mail message.</param>
        /// <returns></returns>
        public void SendEmail(MailMessage mailMessage)
        {
            ThreadPool.QueueUserWorkItem(callback =>
                {
                    using (mailMessage)
                    {
                        using (var mailClient = new SmtpClient())
                        {
                            var enableSslSetting = ConfigurationManager.AppSettings["EnableSSLOnMail"];
                            bool enableSsl;
                            if (bool.TryParse(enableSslSetting, out enableSsl))
                                mailClient.EnableSsl = enableSsl;

                            mailClient.Send(mailMessage);
                        }
                    }
                });
        }

        /// <summary>
        /// Sends the email.
        /// </summary>
        /// <param name="toEmail">The recipient of this email message.</param>        
        /// <param name="mailMessage">The mail message.</param>
        /// <returns></returns>
        public void SendEmail(string toEmail, MailMessage mailMessage)
        {
            SendEmail(new MailAddress(toEmail), mailMessage);
        }

        /// <summary>
        /// Sends the email.
        /// </summary>
        /// <param name="toEmail">The recipient of this email message.</param>
        /// <param name="mailMessage">The mail message.</param>
        public void SendEmail(MailAddress toEmail, MailMessage mailMessage)
        {
            mailMessage.To.Add(toEmail);
            SendEmail(mailMessage);
        }
    }
}
